<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useDidShow, usePullDownRefresh, useReachBottom, useReady } from '@tarojs/taro';
import { Edit, Uploader } from '@nutui/icons-vue-taro';
import defaultBg from '@/assets/image/default.png';
import type { Book } from '@/interface';
import { pageBook } from '@/service/api';
import { getRequestUrl } from '@/service/request/helpers';

const bookList = ref<Array<Book>>([]);

/**
 * 初始化分页请求参数
 */
const initPageParam = () => {
  return {
    current: 1,
    size: 10,
    orderItems: new Array<Common.OrderItem>({
      column: 'createAt',
      asc: false
    })
  } as Common.Page<Book>;
};

const pageParam = ref<Common.Page<Book>>(initPageParam());
const flushed = ref<boolean>(true);

const requestPage = (data: Common.Page<Book>) => {
  pageBook(data).then((res: Service.SuccessResult) => {
    if (res.success && res.success.records && res.success.records.length) {
      bookList.value = [...bookList.value, ...res.success.records];
    } else {
      flushed.value = false;
    }
  });
};

const flushData = () => {
  flushed.value = true;
  pageParam.value = initPageParam();
  bookList.value = [];
  requestPage(pageParam.value);
};

const onBookClick = (row: Book) => {
  Taro.navigateTo({
    url: `/package/receiving/index?bookId=${row.id}`,
    success(res) {
      res.eventChannel.emit('initData', row);
    }
  });
};

const onCreate = () => {
  Taro.navigateTo({
    url: '/package/book-adder/index',
    events: {
      flushData() {
        flushData();
      }
    }
  });
};

const onSetting = (row: Book) => {
  Taro.navigateTo({
    url: '/package/book-adder/index?tag=setting',
    events: {
      flushData() {
        flushData();
      }
    },
    success(res) {
      res.eventChannel.emit('initData', row);
    }
  });
};

const stickyHeight = ref<number>(0);
useReady(() => {
  Taro.nextTick(() => {
    Taro.createSelectorQuery()
      .select('#book-nav-bar')
      .boundingClientRect()
      .exec(res => {
        const { bottom } = res[0];
        stickyHeight.value = bottom;
      });
  });
});

usePullDownRefresh(() => {
  Taro.showLoading({
    title: '加载中...',
    mask: true
  });
  flushData();
  Taro.stopPullDownRefresh();
  Taro.hideLoading();
});

useReachBottom(() => {
  if (flushed.value) {
    Taro.showLoading({
      title: '加载中...',
      mask: true
    });
    pageParam.value.current += 1;
    requestPage(pageParam.value);
    Taro.hideLoading();
  }
});

onMounted(() => {
  pageParam.value = initPageParam();
  requestPage(pageParam.value);
});
</script>

<template>
  <basic-layout show-tab-bar>
    <custom-nav-bar id="book-nav-bar" title="礼簿" />
    <div class="w-375px text-30px text-primary bg-#fafafa">
      <div class="w-full h-12px"></div>
      <nut-sticky :top="stickyHeight">
        <nut-button block class="hoo-btn hoo-btn--dashed" @click="onCreate">
          <template #icon>
            <Uploader color="#9ca3af" size="12px" />
          </template>
          <template #default>
            <span class="color-#9ca3af text-12px">点击创建礼簿</span>
          </template>
        </nut-button>
      </nut-sticky>
      <nut-cell v-for="(item, index) in bookList" :key="index" center class="book-cell" @click="onBookClick(item)">
        <template #icon>
          <image
            class="w-120px h-80px b-rd-5px shadow"
            :src="getRequestUrl('/admin' + item.coverPath) || defaultBg"
            alt=""
          />
        </template>
        <template #title>
          <div class="block text-center w-140px">
            <div class="flex-center font-bold text-16px">{{ item.bookName }}</div>
            <div class="inline-block vertical-mid mt-10px text-12px">
              <span class="block w-40px text-right">收礼</span>
              <nut-divider direction="vertical" style="color: #666; border-color: #666" />
              <span class="block w-40px text-left">回礼</span>
            </div>
            <div class="inline-block vertical-mid">
              <nut-price
                class="book-count receiving"
                :price="item.receivingCount || 0"
                :decimal-digits="0"
                symbol="笔"
                position="after"
              />
              <nut-divider direction="vertical" style="color: #666; border-color: #666" />
              <nut-price
                class="book-count reciprocation"
                :price="item.reciprocationCount || 0"
                :decimal-digits="0"
                symbol="笔"
                position="after"
              />
            </div>
          </div>
        </template>
        <template #link>
          <div
            class="w-50px h-50px absolute right-0 top-0 flex justify-center items-center"
            @click.stop="onSetting(item)"
          >
            <Edit color="#666666" size="16px" />
          </div>
        </template>
      </nut-cell>
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';

.book-cell {
  width: 92%;
  margin: 12px auto 0;
  border-radius: 6px;
}

.book-count {
  display: inline-block;
  justify-content: center;
  align-items: baseline;
  width: 60px;

  .nut-price--normal {
    font-size: 14px;
  }

  .nut-price--symbol {
    font-size: 10px;
  }
}

.receiving {
  color: #666;
  text-align: right;
}

.reciprocation {
  color: #666;
  text-align: left;
}
</style>
